#include "profile.h"
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPixmap>
#include <QTextEdit>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QMessageBox>

#include <opencv2/opencv.hpp>
#include <qstandarditemmodel.h>

#include "ElaText.h"
#include "ElaPushButton.h"
#include "ElaLineEdit.h"
#include "ElaComboBox.h"
#include "ElaIcon.h"
#include "ElaScrollPageArea.h"
#include "ElaTableView.h"
#include "delegate.h"

//Q_TAKEOVER_NATIVEEVENT_CPP(profile, d_func()->_appBar);
profile::profile(ElaWidget *parent)
    : ElaWidget{parent}
{
    //(Qt::FramelessWindowHint | Qt::Window);
    //setAttribute(Qt::WA_TranslucentBackground);
    /*ElaAppBar *pBar = new ElaAppBar(this);
    pBar->setWindowButtonFlag(ElaAppBarType::StayTopButtonHint,false);
    pBar->setWindowButtonFlag(ElaAppBarType::ThemeChangeButtonHint,false);
    pBar->setWindowButtonFlag(ElaAppBarType::RouteBackButtonHint,false);
    pBar->setAppBarHeight(60);*///这部分代码时自己设计的标题栏，现在不用了。



    /*if(color == 0)
    {
        setStyleSheet("background-color: #333333; color: white;");
    }
    else
    {
        setStyleSheet(" color: black;");
    }*//*
*/

    setWindowTitle("病人资料卡");
    resize(1024,720);
    this->setIsFixedSize(true);
    QPixmap p (":/resource/Image/Cirno.jpg");
   // QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(this);
    QHBoxLayout *picLayout = new QHBoxLayout(this);
    QLabel *pic = new QLabel();
    ElaText *text0 = new ElaText("姓名",this);
    text0->setTextStyle(ElaTextType::TextStyle::Body);
    text0->setTextPixelSize(15);
    ElaText *text1 = new ElaText("编号",this);
    text1->setTextStyle(ElaTextType::TextStyle::Body);
    text1->setTextPixelSize(15);
    ElaText *text2 = new ElaText("年龄",this);
    text2->setTextStyle(ElaTextType::TextStyle::Body);
    text2->setTextPixelSize(15);
    ElaText *text3 = new ElaText("性别",this);
    text3->setTextStyle(ElaTextType::TextStyle::Body);
    text3->setTextPixelSize(15);
    ElaText *text4 = new ElaText("病区",this);
    text4->setTextStyle(ElaTextType::TextStyle::Body);
    text4->setTextPixelSize(15);
    ElaText *text5 = new ElaText("异常行为",this);
    text5->setTextStyle(ElaTextType::TextStyle::Body);
    text5->setTextPixelSize(15);
    ElaText *text6 = new ElaText("备注",this);
    text6->setTextStyle(ElaTextType::TextStyle::Body);
    text6->setTextPixelSize(15);
    ElaText *informationText = new ElaText("病人基本信息",this);
    informationText->setTextStyle(ElaTextType::TextStyle::Title);
    QHBoxLayout *infortitleLayout = new QHBoxLayout();
    infortitleLayout->addStretch();
    infortitleLayout->addWidget(informationText);
    infortitleLayout->addStretch();

    pic->setFixedSize(475,300);
    pic->setScaledContents(true);
    pic->setPixmap(p);
    picLayout->addWidget(pic);

    QHBoxLayout *lineLayout0 = new QHBoxLayout(this);
    QHBoxLayout *lineLayout1 = new QHBoxLayout(this);
    QVBoxLayout *lineLayout2 = new QVBoxLayout(this);
    QVBoxLayout *lineLayout3 = new QVBoxLayout(this);
    lineLayout0->setContentsMargins(0,0,0,0);
    lineLayout1->setContentsMargins(0,0,0,0);
    lineLayout2->setContentsMargins(0,0,0,0);
    lineLayout3->setContentsMargins(0,0,0,0);
    ElaLineEdit *name = new ElaLineEdit(this);
    name->setFixedSize(100,25);
    //ElaLineEdit *number = new ElaLineEdit(this);
    ElaComboBox *number = new ElaComboBox(this);
    number->setFixedWidth(150);
    ElaLineEdit *age = new ElaLineEdit(this);
    age->setFixedSize(100,25);
    ElaLineEdit *gender = new ElaLineEdit(this);
    gender->setFixedSize(100,25);
    ElaLineEdit *zone = new ElaLineEdit(this);
    zone->setFixedSize(100,25);
    ElaTableView *manner =new ElaTableView(this);
    QStandardItemModel *tableModel = new QStandardItemModel(this);
    tableModel->setHorizontalHeaderLabels({"时间", "异常行为"});
    manner->setModel(tableModel);
    manner->setFixedSize(450,200);
    manner->setColumnWidth(0, 200);
    manner->setColumnWidth(1, 250);
    delegate *dgate = new delegate(this);
    manner->setItemDelegateForColumn(0,dgate);
    //QTextEdit *manner = new QTextEdit(this);
    //manner->setFixedSize(370,100);
    QTextEdit *notes = new QTextEdit(this);
    notes->setFixedSize(450,200);

    lineLayout0->addStretch();
    lineLayout0->addSpacing(5);
    lineLayout0->addWidget(text0);
    lineLayout0->addWidget(name);
    lineLayout0->addSpacing(50);
    lineLayout0->addWidget(text1);
    lineLayout0->addWidget(number);
    lineLayout0->addStretch();

    lineLayout1->addStretch();
    lineLayout1->setSpacing(5);
    lineLayout1->addWidget(text2);
    lineLayout1->addWidget(age);
    lineLayout1->addSpacing(50);
    lineLayout1->addWidget(text3);
    lineLayout1->addWidget(gender);
    lineLayout1->addSpacing(50);
    lineLayout1->addWidget(text4);
    lineLayout1->addWidget(zone);
    lineLayout1->addStretch();

    ElaScrollPageArea *informationArea = new ElaScrollPageArea(this);
    informationArea->setFixedSize(475,300);
    QVBoxLayout *informLayout = new QVBoxLayout(informationArea);
    informLayout->setContentsMargins(0,0,0,0);
    informLayout->addStretch();
    informLayout->addLayout(infortitleLayout);
    informLayout->addLayout(lineLayout0);
    informLayout->addLayout(lineLayout1);
    informLayout->addStretch();

    QHBoxLayout *headerLayout = new QHBoxLayout();
    headerLayout->setContentsMargins(0,0,0,0);
    headerLayout->addWidget(informationArea);
    headerLayout->addLayout(picLayout);

    QHBoxLayout *mannertitleLayout = new QHBoxLayout();
    ElaText *mannerText = new ElaText("病人行为记录",this);
    mannerText->setTextStyle(ElaTextType::TextStyle::Title);
    QHBoxLayout *textLayout0 = new QHBoxLayout();
    textLayout0->addStretch();
    textLayout0->addWidget(text5);
    textLayout0->addStretch();

    QHBoxLayout *textLayout1 = new QHBoxLayout();
    textLayout1->addStretch();
    textLayout1->addWidget(text6);
    textLayout1->addStretch();

    mannertitleLayout->addStretch();
    mannertitleLayout->addWidget(mannerText);
    mannertitleLayout->addStretch();

    lineLayout2->addStretch();
    lineLayout2->addSpacing(5);
    lineLayout2->addLayout(textLayout0);
    lineLayout2->addWidget(manner);
    //lineLayout2->addStretch();

    //lineLayout3->addStretch();
    lineLayout3->addSpacing(30);
    lineLayout3->addLayout(textLayout1);
    lineLayout3->addWidget(notes);
    lineLayout3->addStretch();

    QHBoxLayout *mannerLayout = new QHBoxLayout();
    mannerLayout->addLayout(lineLayout2);
    mannerLayout->addLayout(lineLayout3);

    ElaScrollPageArea *mannerArea = new ElaScrollPageArea(this);
    mannerArea->setFixedSize(1000,300);
    QVBoxLayout *mannertotalLayout = new QVBoxLayout(mannerArea);
    mannertotalLayout->setContentsMargins(50,0,0,0);
    mannertotalLayout->addLayout(mannertitleLayout);
    mannertotalLayout->addLayout(mannertotalLayout);
    mannertotalLayout->addLayout(mannerLayout);



    layout->addLayout(headerLayout);
    //layout->addSpacing(50);
    /*layout->addLayout(lineLayout0);
    layout->addLayout(lineLayout1);
    layout->addLayout(lineLayout2);
    layout->addLayout(lineLayout3);*/
    layout->addWidget(mannerArea);
    QHBoxLayout *baseinformationLayout= new QHBoxLayout();

    ElaPushButton *saveButton = new ElaPushButton(this);
    saveButton->setText("保存");
    ElaPushButton *cancelButton = new ElaPushButton(this);
    cancelButton->setText("取消");
    QHBoxLayout *btnLayout = new QHBoxLayout(this);
    btnLayout->addStretch();
    btnLayout->addWidget(saveButton);
    btnLayout->setSpacing(50);
    btnLayout->addWidget(cancelButton);
    btnLayout->addStretch();

    layout->addLayout(btnLayout);


    connect(name,&ElaLineEdit::textChanged,this,[=](){
        QString getName = name->text();
        QString pfileName = filePath+"/patient/"+getName+".txt";

        if(getName != "" )
        {
            number->setEditable(true);
        }
        else
        {
            number->setEditable(false);
        }
        /*name->clear();
        number->clear();
        gender->clear();
        age->clear();*/
        //manner->clear();

        //QString fileName = QDir::currentPath();
        qDebug()<<pfileName;
        if(QFile::exists(pfileName))
        {       
            qDebug()<<"file: [" << pfileName << "] found";
            Found = 1;
            QFile pf(pfileName);
            pf.open(QIODevice::ReadOnly);
            QTextStream pin(&pf);
            QString pline;
            QString pcurrentRegion = "";
            while(!pin.atEnd())
            {
                pline = pin.readLine();
                if(pline.startsWith('[') && pline.endsWith(']'))
                {
                    pcurrentRegion = pline;
                    continue;
                }
                if(pcurrentRegion == "[name]")
                {
                    name->setText(pline);
                }
                else if(pcurrentRegion == "[Id]")
                {
                    /*if(color == 0)
                    {
                        number->setStyleSheet("color:white");
                    }
                    else
                    {
                        number->setStyleSheet("color:black");
                    }*/
                    number->addItem(pline);
                }
            }
            pf.close();
        }
        else
        {
            // qDebug() << "profile: file not found";
            qDebug()<<"profile: file: [" << pfileName << "] not found";
            number->clear();
            QStandardItem *item = new QStandardItem(Time);
            if(color == 0 )
                item->setForeground(Qt::white);
            else
                item->setForeground(Qt::black);
            tableModel->setItem(0,0,item);
            tableModel->setHorizontalHeaderLabels({"时间", "异常行为"});
            manner->setColumnWidth(1,300);
            manner->resizeColumnToContents(0);
        }
    });


    connect(number,QOverload<int>::of(&ElaComboBox::currentIndexChanged),this,[=](int i){
        int rowCount = 0;

        //name->clear();
        //number->clear();
        gender->clear();
        age->clear();
        zone->clear();
        tableModel->clear();
        notes->clear();

        QString getName = name->text();
        QString getNumber = number->currentText();
        QString fileName = filePath+"/document/"+getName+'_'+getNumber+".txt";

        if(QFile::exists(fileName))
        {
            qDebug()<<fileName;

            QFile f(fileName);
            f.open(QIODevice::ReadOnly);
            QTextStream in(&f);
            QString line;
            QString currentRegion = "";
            while(!in.atEnd())
            {
                line = in.readLine();
                if(line.startsWith('[') && line.endsWith(']'))
                {
                    currentRegion = line;
                    if(currentRegion == "[manner]")
                        rowCount = 0;
                    continue;
                }
                if(currentRegion == "[age]")
                {
                    age->setText(line);
                }else if(currentRegion == "[gender]")
                {
                    gender->setText(line);
                }
                else if(currentRegion == "[time]")
                {
                    QStandardItem *item = new QStandardItem(line);
                    if(color == 0 )
                        item->setForeground(Qt::white);
                    else
                        item->setForeground(Qt::black);
                    rowCount = tableModel->rowCount();
                    tableModel->insertRow(rowCount);
                    tableModel->setItem(rowCount,0,item);
                    tableModel->setHorizontalHeaderLabels({"时间", "异常行为"});
                    manner->resizeColumnToContents(0);
                    manner->setColumnWidth(1,300);
                    //manner->append(line);
                }else if(currentRegion == "[manner]")
                {
                    QStandardItem *item = new QStandardItem(line);
                    tableModel->setItem(rowCount,1,item);
                    //tableModel->setHorizontalHeaderLabels({"时间", "异常行为"});
                    manner->resizeColumnToContents(0);
                    manner->setColumnWidth(1,300);
                    rowCount++;
                    int maxRow = tableModel->rowCount();
                    qDebug()<<"max"<<maxRow;
                    if(rowCount == maxRow)
                    {
                        QStandardItem *itemTime = new QStandardItem(Time);
                        if(color == 0 )
                            itemTime->setForeground(Qt::white);
                        else
                            itemTime->setForeground(Qt::black);
                        tableModel->insertRow(rowCount);
                        tableModel->setItem(rowCount,0,itemTime);
                        tableModel->setHorizontalHeaderLabels({"时间", "异常行为"});
                        manner->resizeColumnToContents(0);
                        manner->setColumnWidth(1,300);
                    }
                }
                else if(currentRegion == "[notes]")
                {
                    notes->append(line);
                }
                else if(currentRegion == "[zone]")
                {
                    zone->setText(line);
                }
                else if(currentRegion == "[date]")
                {
                    _date = line;
                }
                else if(currentRegion == "[diagnosis]")
                {
                    _diagnosis = line;
                }
                else if(currentRegion == "[bodycheck]")
                {
                    _bodycheck = line;
                }
                else if(currentRegion == "[complaint]")
                {
                    _complaint = line;
                }
                else if(currentRegion == "[presenthistory]")
                {
                    _presenthistory = line;
                }
                else if(currentRegion == "[anamnesis]")
                {
                    _anamnesis = line;
                }

            }
            f.close();
            //Found = 0;
        }
        else
        {
            QStandardItem *item = new QStandardItem(Time);
            if(color == 0 )
                item->setForeground(Qt::white);
            else
                item->setForeground(Qt::black);
            tableModel->setItem(0,0,item);
            tableModel->setHorizontalHeaderLabels({"时间", "异常行为"});
            manner->setColumnWidth(1,300);
            manner->resizeColumnToContents(0);
        }

    });



    connect(saveButton,&ElaPushButton::clicked,this,[=]{
        int ret =QMessageBox::question(this ,"保存","您确定要保存吗？", QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
        if(ret == QMessageBox::Yes)
        {
            int rowCount = 0;
            QString getName = name->text();
            QString getNum = number->currentText();
            QString getGen = gender->text();
            QString getAge = age->text();
            QString getZone =zone->text();
            //QString getManner ="";

            QString pfileName = filePath+"/patient/"+getName+".txt";
            QString fileName = filePath+"/document/"+getName+'_'+getNum+".txt";

            if(getName == "")
            {
               QMessageBox::critical(this,"提示","请填写病人姓名！");
            }
            else if(getNum == "")
            {
               QMessageBox::critical(this,"提示","请填写病人编号！");
            }
            else if(getAge == "")
            {
                QMessageBox::critical(this,"提示","请填写病人年龄！");

            }
            else if(getGen == "")
            {
                QMessageBox::critical(this,"提示","请填写病人性别！");
            }
            else if(getZone == "")
            {
                QMessageBox::critical(this,"提示","请填写病人所在病区！");
            }
            else
            {
                rowCount = tableModel->rowCount();
                QStandardItem *isNothing = tableModel->item(rowCount-1, 1);
                if (!isNothing || isNothing->text().isEmpty()) {
                    // item 为空或者 item 的文本为空
                    QMessageBox::critical(this,"提示","请填写病人异常行为！");
                }
                //qDebug()<<"行数是："<<rowCount-1;
                else
                {
                    QFile pf(pfileName);
                    pf.open(QIODevice::WriteOnly | QIODevice::Text);
                    QTextStream out0(&pf);

                    QFile f(fileName);
                    f.open(QIODevice::WriteOnly | QIODevice::Text);
                    QTextStream out1(&f);

                    out0<<"[name]\n";
                    out0<<name->text()+'\n';
                    out0<<"[Id]\n";
                    int count = number->count();
                    for (int i = 0; i < count; i++)
                    {
                        QString itemText = number->itemText(i);
                        out0<<itemText+'\n';
                        qDebug() << itemText;
                    }
                    out1<<"[name]\n";
                    out1<<name->text()+'\n';
                    out1<<"[gender]\n";
                    out1<<gender->text()+'\n';
                    out1<<"[age]\n";
                    out1<<age->text()+'\n';
                    out1<<"[zone]\n";
                    out1<<zone->text()+'\n';
                    out1<<"[Id]\n";
                    out1<<number->currentText()+'\n';
                    out1<<"[date]\n";
                    out1<<_date+'\n';
                    out1<<"[diagnosis]\n";
                    out1<<_diagnosis+'\n';
                    out1<<"[bodycheck]\n";
                    out1<<_bodycheck+'\n';
                    out1<<"[complaint]\n";
                    out1<<_complaint+'\n';
                    out1<<"[presenthistory]\n";
                    out1<<_presenthistory+'\n';
                    out1<<"[anamnesis]\n";
                    out1<<_anamnesis+'\n';
                    out1<<"[time]\n";
                    for(int i = 0;i<rowCount;i++)
                    {
                        QString timeText = tableModel->item(i,0)->text();
                        out1<<timeText+'\n';
                    }
                    out1<<"[manner]\n";
                    for(int j = 0;j<rowCount;j++)
                    {
                        QString mannerText = tableModel->item(j,1)->text();
                        out1<<mannerText+'\n';
                    }
                    //out<<manner->toPlainText()+'\n';
                    out1<<"[notes]\n";
                    out1<<notes->toPlainText()+'\n';
                    deleteflag = 1;
                    QMessageBox::information(this,"","保存成功");
                    name->clear();
                    number->clear();
                    gender->clear();
                    age->clear();
                    tableModel->clear();
                    notes->clear();
                    pf.close();
                    f.close();
                    this->close();
                }
            }
        }
    });


    connect(cancelButton,&ElaPushButton::clicked,this,[=]{
        this->close();
        name->clear();
        number->clear();
        gender->clear();
        age->clear();
        tableModel->clear();
        notes->clear();
    });


}



void profile::findDoc()
{

}
